﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using Facebook;
using FacebookAcessLibrary.Data;

namespace FacebookAcessLibrary.FacebookClass
{
    public class Notification
    {
        //private string f = "141208535946866|d2bff2a353b2f1e2a128c359.1-100000160481614|WdQR9GRGnrUmMGPpjLrkVRPyfZA";


        private readonly FacebookClient _client = new FacebookClient("141208535946866", "378a4f4d0672dd55c7a21ab9362544df");
        public void NotifyUsers(IEnumerable<long> uids, string messageNotification, Uri callback)
        {

            dynamic parameters = new ExpandoObject();

            parameters.news = new ArrayList();
            parameters.news.Add(new
            {
                message = messageNotification,
                action_link = new { text = "Notification", href = callback.AbsoluteUri }
            });
            parameters.method = "dashboard.addNews";

            foreach (var idUser in uids)
            {
                parameters.uid = idUser;
                _client.Post(parameters);

            }

        }

        public List<NotificationData> GetNotificationUser(long uid)
        {
            dynamic parameters = new ExpandoObject();
            parameters.uid = uid;
            parameters.method = "dashboard.getNews";


            dynamic aux = _client.Post(parameters);
            if (aux.Count == 0) return null;
            JsonObject data = aux;
            return data.Keys.Select(k => WrapperNotification(data[k], long.Parse(k))).ToList();

        }

        public void ClearNotificationUser(IEnumerable<long> notification, long uid)
        {
            dynamic parameters = new ExpandoObject();
            parameters.uid = uid;
            if (notification != null)
            {
                parameters.news_ids = new ArrayList();
                foreach (var n in notification)
                {
                    parameters.news_ids.Add(n);

                }
            }
            parameters.method = "dashboard.clearNews";
            _client.Post(parameters);
        }

        

        private static NotificationData WrapperNotification(dynamic notification, long key)
        {
            var data = new NotificationData
            {
                Key = key,
                Image = notification.image,
                News = new News
                {
                    Message = notification.news[0].message,
                    Action = new ActionLink
                    {
                        Text =
                            notification.news[0].
                            action_link.text,
                        Href =
                            notification.news[0].
                            action_link.href
                    }
                }
            };
            return data;
        }
    }

}
